import { defineStore } from "pinia";
import { ref } from "vue";
import type { Ref } from "vue";
import type { Patient } from "@/types/patientTypes";
import { addPatientAPI, deletePatientAPI, editPatientAPI, fetchPatientAPI, findPatientAPI } from "@/api/patientApi.ts";

export const usePatientStore = defineStore("patientStore", () => {
    /*患者列表*/
    const patientList: Ref<Patient[]> = ref<Patient[]>([]);
    /*控制编辑状态*/
    const edit: Ref<boolean> = ref<boolean>(false);
    /*控制弹出层的显示*/
    const showPopup: Ref<boolean> = ref<boolean>(false);
    /*获取患者列表的请求函数*/
    const fetchPatient = async (): Promise<void> => {
        const { data }: { data: Patient[] } = await fetchPatientAPI();
        patientList.value = data;
    };

    /*删除患者列表的请求函数*/
    const deletePatient = async (patientId: string): Promise<void> => {
        await deletePatientAPI(patientId);
        patientList.value = patientList.value.filter((item: Patient): boolean => item.id !== patientId);
    };

    /*添加患者列表的请求函数*/
    const addPatient = async (data: Patient): Promise<void> => {
        await addPatientAPI(data);
    };

    /*修改患者列表的请求函数*/
    const updatePatient = async (data: Patient): Promise<void> => {
        await editPatientAPI(data);
    };

    /*查找患者的请求函数*/
    const findPatient = async (id: string): Promise<Patient> => {
        const { data }: { data: Patient } = await findPatientAPI(id);
        return data;
    };

    const changeShowPopup = (flag: boolean): void => {
        showPopup.value = flag;
    };

    const changeEdit = (flag: boolean): void => {
        edit.value = flag;
    };
    return {
        patientList,
        edit,
        showPopup,
        fetchPatient,
        deletePatient,
        addPatient,
        updatePatient,
        findPatient,
        changeShowPopup,
        changeEdit,
    };

});


export default usePatientStore;
